<?php
    include(dirname(__FILE__)."/../../../Dao/db.php");
    include(dirname(__FILE__)."/../../../domain_url.php");

    class KeywordService
    {
        var $memberId;
        //メディア種類
        var $listingType;
        //キャンペーンID
        var $camp_Id;
        //キャンペーン名
        var $campaignName;
        //広告グループID
        var $adGr_Id;
        //広告グループ名
        var $adGroupName;
        //キーワードID
        var $key_Id;
        //キーワードテキスト
        var $keywordName;
        //キーワードの重複許可
        var $duplicate;
        //代替テキスト
        var $insteadWord;
        //マッチタイプ
        var $matchType;
        //スポンサードサーチ
        var $maxCpc;
        //掲載状態
        var $isPaused;
        //ランディング先URL
        var $destinationUrl;
        //ドメインＵＲＬ
        var $domain;

        function KeywordService()
        {
            session_start();
            $this->memberId= $_SESSION['memberId'];
            $this->listingType = $_GET['listingType'];
            $this->camp_Id = $_GET['campaignId'];
            $this->campaignName = $this->getCampaignName($this->camp_Id);
            $this->adGr_Id = $_GET['adGroupId'];
            $this->adGroupName = $this->getAdGroupName($this->adGr_Id);
            $this->key_Id = $_GET['keywordId'];
            $this->keywordName = $_POST['keyword_name'];
            $this->insteadWord = $_POST['alternate_text'];
            $this->duplicate = $_POST['keyword_duplicate'];
            $this->matchType = $_POST['sponsored_search'];
            if(isset($_POST['sponsored_maxbid']) && $_POST['sponsored_maxbid'] != 0)
            {
                $this->maxCpc = $_POST['sponsored_maxbid'];
            }
            else
            {
                $this->maxCpc = 0;
            }

            if($_POST['status'] == 0)
            {
                $this->isPaused = 1;
            }
            else
            {
                $this->isPaused = 0;
            }

            $this->destinationUrl = $_POST['landing_url_keyword'];

            $this->domain = DOMAIN_URL."?key_Id=";
        }

        function getCampaignName($camp_Id)
        {
            $query = "SELECT  name ";
            $query .= "FROM   campaign ";
            $query .= "WHERE  camp_Id=$camp_Id";
            $result = mysql_query($query);
            $row = mysql_fetch_array($result);
            return $row['name'];
        }

        function getAdGroupName($adGr_Id)
        {
            $query = "SELECT  name ";
            $query .= "FROM   adgroup ";
            $query .= "WHERE  adGr_Id=$adGr_Id";
            $result = mysql_query($query);
            $row = mysql_fetch_array($result);
            return $row['name'];
        }

        //同期エラーを表示する
        function getErrorMessage()
        {
            $query = "SELECT syncError FROM keyword ";
            $query .= "WHERE key_Id=$this->key_Id ";
            $query .= "AND sync=3 ";

            $result = mysql_query($query);
            $row = mysql_fetch_array($result);
            $syncError = trim($row['syncError']);
            if($syncError)
            {
                $errorTable = "<br><table class='tbl' width='100%' border='0' cellpadding='4' cellspacing='0'>";
                $errorTable .= "<tbody><tr>";
                $errorTable .= "<td class='td9' width='150' align='left'>";
                $errorTable .= "<img src='../images/sync_error.gif' border='0'>エラー</td>";
                $errorTable .= "<td class='td4 left'><pre>".$syncError."</pre></td>";
                $errorTable .= "</tr></tbody>";
                $errorTable .= "</table><br>";
            }

            echo $errorTable;
        }

        function addKeyword()
        {
            //同一媒体内では許可しない
            if($this->duplicate == 0)
            {
                $query = "SELECT * FROM keyword WHERE ";
                $query .= "memberId=$this->memberId AND ";
                $query .= "listingType=$this->listingType AND ";
                $query .= "text='$this->keywordName' AND ";
                //削除したキーワードは除外
                $query .= "status!=9";
                $result = mysql_query($query);
                unset($query);

                if(!mysql_fetch_array($result))
                {
                    $insert = true;
                }
                else
                {
                    $message = "同一媒体に同じキーワードがある";
                }
            }
            //同一キャンペーン内では許可しない
            else if($this->duplicate == 1)
            {
                $query = "SELECT * FROM keyword WHERE ";
                $query .= "camp_Id=$this->camp_Id AND ";
                $query .= "text='$this->keywordName' AND ";
                //削除したキーワードは除外
                $query .= "status!=9";

                $result = mysql_query($query);
                unset($query);

                if(!mysql_fetch_array($result))
                {
                    $insert = true;
                }
                else
                {
                    $message = "同一キャンペーンに同じキーワードがある";
                }
            }
            //同一広告グループ内では許可いさい
            else
            {
                $query = "SELECT * FROM keyword WHERE ";
                $query .= "adGr_Id=$this->adGr_Id AND ";
                $query .= "text='$this->keywordName' AND ";
                //削除したキーワードは除外
                $query .= "status!=9";

                $result = mysql_query($query);
                unset($query);

                if(!mysql_fetch_array($result))
                {
                    $insert = true;
                }
                else
                {
                    $message = "同一広告グループに同じキーワードがある";
                }
            }

            if(isset($insert))
            {
                $now = $now = date("Y-m-d H:i:s");
                $query = "INSERT INTO keyword (memberId,listingType,camp_Id,adGr_Id,text,";
                $query .= "replaceText,type,maxCpc,";
                $query .= "destinationUrl,paused,sync,registDate,lastUpdate) ";
                $query .= "VALUES($this->memberId,";
                $query .= "$this->listingType,";
                $query .= "$this->camp_Id,";
                $query .= "$this->adGr_Id,";
                $query .= "'$this->keywordName',";
                $query .= "'$this->insteadWord',";
                $query .= "$this->matchType,";
                $query .= "$this->maxCpc,";
                $query .= "'$this->destinationUrl',";
                $query .= "$this->isPaused,";
                //Googleに未同期
                $query .= "2,";
                $query .= "'$now','$now')";

                $result = mysql_query($query);
                if ($result != "1")
                {
                    $message = "登録失敗しました";
                }
                else
                {
                    $query = "update keyword set redirectUrl=CONCAT('$this->domain',key_Id) ";
                    $query .= "where adGr_Id=$this->adGr_Id and lastUpdate='$now'";
                    mysql_query($query);
                    $message = "登録しました";
                }
            }
            return $message;
        }

        function updateKeyword()
        {
            //該当キーワードのマッチタイプを検索
//            $query = "SELECT type FROM keyword WHERE ";
//            $query .= "key_Id=$this->key_Id";
//            $result = mysql_query($query);
//            $row=mysql_fetch_array($result);
//            $matchType = $row['type'];
//
//            if($matchType != $this->matchType)
//            {
//                //テキストとマッチタイプも変更しない場合、画面からの情報に基づいて、新しいキーワードを挿入
//                $now = $now = date("Y-m-d H:i:s");
//                $query = "INSERT INTO keyword (memberId,listingType,camp_Id,adGr_Id,text,";
//                $query .= "replaceText,type,maxCpc,";
//                $query .= "destinationUrl,paused,sync,registDate,lastUpdate) ";
//                $query .= "VALUES($this->memberId,";
//                $query .= "$this->listingType,";
//                $query .= "$this->camp_Id,";
//                $query .= "$this->adGr_Id,";
//                $query .= "'$this->keywordName',";
//                $query .= "'$this->insteadWord',";
//                $query .= "$this->matchType,";
//                $query .= "$this->maxCpc,";
//                $query .= "'$this->destinationUrl',";
//                $query .= "$this->isPaused,";
//                //Googleに未同期
//                $query .= "2,";
//                $query .= "'$now','$now')";
//
//                $result = mysql_query($query);
//                if ($result != "1")
//                {
//                    $message = "更新失敗しました";
//                }
//                else
//                {
//                    $query = "update keyword set redirectUrl=CONCAT('$this->domain',key_Id) ";
//                    $query .= "where adGr_Id=$this->adGr_Id and lastUpdate='$now'";
//                    mysql_query($query);
//                    //旧なキーワード削除
//                    $query = "UPDATE keyword SET status=9,sync=2,lastUpdate=now() WHERE ";
//                    $query .= "key_Id=$this->key_Id";
//                    $result = mysql_query($query);
//                    $message = "更新しました";
//                }
//
//            }
//            else
//            {
                //テキストとマッチタイプも変更されない場合、該当キーワードをGoogleに更新
                $query = "UPDATE keyword SET ";
                $query .= "replaceText='$this->insteadWord',";
                $query .= "paused=$this->isPaused,";
                $query .= "maxCpc=$this->maxCpc,";
                $query .= "type=$this->matchType,";
                $query .= "destinationUrl='$this->destinationUrl',";
                $query .= "sync=2,lastUpdate=now() WHERE ";
                $query .= "key_Id=$this->key_Id";

                $result = mysql_query($query);
                if ($result != "1")
                {
                    $message = "更新失敗しました";
                }
                else
                {
                    $message = "更新しました";
                }
//            }
            return $message;
        }

        function updateAllKeywords()
        {
            $keywordIds = split(",",$_GET['keywordIds']);

            $ids = "(";
            for($i=0;$i<count($keywordIds)-1;$i++)
            {
                $ids .=$keywordIds[$i].",";
            }
            $ids .= $keywordIds[count($keywordIds)-1].")";

            $queryHead = "UPDATE keyword SET ";

            if(isset($_POST['change_status']))
            {
                $queryBody = "paused=$this->isPaused,";
            }

            if(isset($_POST['change_bid']))
            {
                if($_POST['change_bid_type'] == "1")
                {
                    if(isset($_POST['type1_maxbid']) && $_POST['type1_maxbid'] != "")
                    {
                    $queryBody .= "maxCpc={$_POST['type1_maxbid']},";
                    }
                    else
                    {
                        $queryBody .= "maxCpc=0,";
                    }
                }
                else if($_POST['change_bid_type'] == "2")
                {
                    $queryBody .= "maxCpc=if(maxCpc*(1+{$_POST['type2_rate']}/100)<={$_POST['type2_maxbid']},maxCpc*(1+{$_POST['type2_rate']}/100),{$_POST['type2_maxbid']}),";
                }
                else if($_POST['change_bid_type'] == "3")
                {
                    $queryBody .= "maxCpc=if(maxCpc*(1-{$_POST['type3_rate']}/100)>={$_POST['type3_maxbid']},maxCpc*(1-{$_POST['type3_rate']}/100),{$_POST['type3_maxbid']}),";
                }
                else
                {
                    $queryBody .= "maxCpc=0,";
                }
            }

            if(isset($_POST['change_url']))
            {
                $queryBody .= "destinationUrl='$this->destinationUrl',";
            }

            if(isset($_POST['change_delete']))
            {
                //この状態の意味は削除された
                $queryBody .= "status=9,";
            }

            if(isset($queryBody))
            {
                $query = $queryHead.$queryBody;
                //更新待ち
                $query .= "sync=2,lastUpdate=now() WHERE ";
                $query .= "key_Id IN $ids";

                $result = mysql_query($query);
                if ($result != "1")
                {
                    $message = "更新失敗しました";
                }
                else
                {
                    $message = "更新しました";
                }
            }
            return $message;
        }

        
    }


?>
